package cn.tanghom.support.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;



/**
 * MD5工具类
 * 
 * @author DongQihong
 * 
 */
public class Md5Util {
	
	private static char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	private static Map<Character, Integer> rDigits = new HashMap<Character, Integer>(16);
	static {
		for (int i = 0; i < digits.length; ++i) {
			rDigits.put(digits[i], i);
		}
	}

	private static ReentrantLock opLock = new ReentrantLock();

	public static final String ENCODE = "UTF-8";
	private static MessageDigest mHasher;
	static {
		try {
			mHasher = MessageDigest.getInstance("md5");
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

	}

	public static String getMD5String(String content) {
		return bytes2string(hash(content));
	}

	public static String getMD5String(byte[] content) {
		return bytes2string(hash(content));
	}

	public static byte[] getMD5Bytes(byte[] content) {
		return hash(content);
	}

	/**
	 * 对字符串进行md5
	 *
	 * @param str
	 * @return md5 byte[16]
	 */
	public static byte[] hash(String str) {
		opLock.lock();
		try {
			byte[] bt = mHasher.digest(str.getBytes(ENCODE));
			if (null == bt || bt.length != 16) {
				throw new IllegalArgumentException("md5 need");
			}
			return bt;
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("unsupported utf-8 encoding", e);
		} finally {
			opLock.unlock();
		}
	}

	/**
	 * 对二进制数据进行md5
	 *
	 * @param str
	 * @return md5 byte[16]
	 */
	public static byte[] hash(byte[] data) {
		opLock.lock();
		try {
			byte[] bt = mHasher.digest(data);
			if (null == bt || bt.length != 16) {
				throw new IllegalArgumentException("md5 need");
			}
			return bt;
		} finally {
			opLock.unlock();
		}
	}

	/**
	 * 将一个字节数组转化为可见的字符串
	 *
	 * @param bt
	 * @return
	 */
	public static String bytes2string(byte[] bt) {
		int l = bt.length;

		char[] out = new char[l << 1];

		for (int i = 0, j = 0; i < l; i++) {
			out[j++] = digits[(0xF0 & bt[i]) >>> 4];
			out[j++] = digits[0x0F & bt[i]];
		}
		return new String(out);
	}

	/**
	 * 将字符串转换为bytes
	 *
	 * @param str
	 * @return byte[]
	 */
	public static byte[] string2bytes(String str) {
		if (null == str) {
			throw new NullPointerException("参数不能为空");
		}
		if (str.length() != 32) {
			throw new IllegalArgumentException("字符串长度必须是32");
		}
		byte[] data = new byte[16];
		char[] chs = str.toCharArray();
		for (int i = 0; i < 16; ++i) {
			int h = rDigits.get(chs[i * 2]).intValue();
			int l = rDigits.get(chs[i * 2 + 1]).intValue();
			data[i] = (byte) ((h & 0x0F) << 4 | (l & 0x0F));
		}
		return data;
	}

	/**
	 * 加密
	 * 
	 * @param str
	 *            要加密的字符串
	 * @return 加密后的32位密文,加密失败返回原字符串.
	 */
	public static String encrypt(String str) {
		MessageDigest messageDigest = null;
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(str.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			return str;
		} catch (UnsupportedEncodingException e) {
			return str;
		}
		byte[] byteArray = messageDigest.digest();
		StringBuffer md5StrBuff = new StringBuffer();
		for (int i = 0; i < byteArray.length; i++) {
			if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
				md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
			} else {
				md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
			}
		}
		return md5StrBuff.toString();
	}

	/**
	 * 验证明文是否与密码对应
	 * 
	 * @param plaintext
	 *            字符串明文
	 * @param ciphertext
	 *            字符md5密文
	 * @return 验证结果，<code>true</code>对应 <code>false</code>不对应
	 */
	public static boolean validate(String plaintext, String ciphertext) {
		return ciphertext.equalsIgnoreCase(encrypt(plaintext));
	}

	public static void main(String[] args) {
		System.out.println(getMD5String("000000"));
	}
}